//
//  WYRefreshControl.swift
//  WYWeibo
//
//  Created by wangyi on 16/7/19.
//  Copyright © 2016年 wangyi. All rights reserved.
//

import UIKit
//控件的高度
private let RefreshControlHeight: CGFloat = 50

//下拉刷新的枚举类型
enum WYRefreshControlStates: Int {

    //下拉状态
    case Normal = 0
    //松手刷新
    case Pulling = 1
    //正在刷新
    case Refreshing = 2
    
}



class WYRefreshControl: UIControl {
    

    //当前下拉刷新的状态
    private var refreshState: WYRefreshControlStates = .Normal {
    
        didSet{
        
            switch refreshState {
            
            case .Normal:
                print("下拉刷新")
                //1 设置内容为下拉刷新 箭头重置
                messageLabel.text = "下拉刷新"
                //显示箭头 关闭风火轮
                iconImageView.hidden = false
                iconImageView.stopAnimating()
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.iconImageView.transform = CGAffineTransformIdentity
                })
                //oldValue 是上一次储存值
                if oldValue == .Refreshing {
                
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        self.currentScrollView?.contentInset.top -= RefreshControlHeight
                    })
                }
            case .Pulling:
                //松手就刷新
                messageLabel.text = "松手就刷新"
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.iconImageView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                
            case .Refreshing:
                print("正在刷新")
            // 设置内容正在刷新 箭头隐藏 显示风火轮
                messageLabel.text = "正在刷新"
                iconImageView.hidden = true
                indicatorView.startAnimating()
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.currentScrollView?.contentInset.top += RefreshControlHeight
                })
                //通知外界加载数据 发送事件
                sendActionsForControlEvents(.ValueChanged)
            }
        }
    }
    //当前滚动视图
    private var currentScrollView: UIScrollView?
    
    //MARK: -- 懒加载控
    
    
    
    //下拉箭头
    private lazy var iconImageView: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    //文字
    private lazy var messageLabel: UILabel = {
    
        let label = UILabel()
        
        label.font = UIFont.systemFontOfSize(14)
        label.textColor = UIColor.redColor()
        label.text = "下拉刷新"
        return label
        
    }()
    //风火轮 控件
    private lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setUpUI() {
    
        self.frame.size = CGSize(width: ScreenWidth, height: RefreshControlHeight)
        self.frame.origin.y = -RefreshControlHeight
        backgroundColor = RandomColor()
   
        
        //设置坐标
        
        addSubview(iconImageView)
        addSubview(messageLabel)
        addSubview(indicatorView)
        
        iconImageView.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: iconImageView, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: -35))
        addConstraint(NSLayoutConstraint(item: iconImageView, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0))
        
        messageLabel.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .Leading, relatedBy: .Equal, toItem: iconImageView, attribute: .Trailing, multiplier: 1, constant: 10))
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .CenterY, relatedBy: .Equal, toItem: iconImageView, attribute: .CenterY, multiplier: 1, constant: 0))
        
        indicatorView.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: .CenterX, relatedBy: .Equal, toItem: iconImageView, attribute: .CenterX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: .CenterY, relatedBy: .Equal, toItem: iconImageView, attribute: .CenterY, multiplier: 1, constant: 0))
        indicatorView.startAnimating()
    }
    //在子视图中将要加入到父控件的时候调用
    override func willMoveToSuperview(newSuperview: UIView?) {
        //判断其父视图是否滚动 判断其父视图是否为  UIScrollView
        guard let scrollView = newSuperview as? UIScrollView else {
        
            return
        }
        //代码执行到此 一定可以滚动
        self.frame.size = CGSize(width: scrollView.frame.size.width, height: RefreshControlHeight)
        self.frame.origin.y = -RefreshControlHeight
        
        //怎样监听父控件的行为  kvo forkeypath: 监听的属性®
        scrollView.addObserver(self, forKeyPath: "contentOffset", options: [.New], context: nil)
        currentScrollView = scrollView
    }
     //监听的方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        //打印偏移量
//        print(currentScrollView?.contentOffset.y)
        
        guard let scrollView = currentScrollView else {
        
            return
        }
        //业务逻辑处理
        //如果推动情况下 下拉刷新  2 松手 刷新的状态
        //如果松手情况下 就要进入正在刷新的状态  前提(当前的刷新状态 松手就刷新的状态)
        
        //因为负数 对临界-114 进行判断 如果小于-114 表示进入的一个松手就刷新的转态
        if scrollView.dragging{
            if scrollView.contentOffset.y < -(scrollView.contentInset.top + RefreshControlHeight) && refreshState == .Normal {
                print("松手刷新")
                refreshState = .Pulling
            } else if scrollView.contentOffset.y >= -(scrollView.contentInset.top + RefreshControlHeight) && refreshState == .Pulling {
                
                print("下拉刷新")
                refreshState = .Normal
            }

        } else {
        
            if refreshState == .Pulling {
            
                refreshState = .Refreshing
                print("正在刷新")
            }
        }
}
    
    
    
    //结束刷新
    func endRefreshing() {
        
        refreshState = .Normal
    }
    
    deinit {
    
        //移除 kvo
        currentScrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }

}
